package org.invigorare.auctions.widgets;

import static org.invigorare.auctions.data.SynchronizableOutboundDataOpener.*;


import static org.invigorare.auctions.data.SaleDataOpener.*;

import org.invigorare.auctions.data.ProduceDataOpener;
import org.invigorare.auctions.data.ProduceDataOpener.*;
import org.invigorare.auctions.R;

import java.util.*;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;

public class SaleItemCursorAdapter extends SimpleCursorAdapter {

	final Context con;
	final String[] cols;
	final int[] views;
	
	public SaleItemCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
		super(context, layout, c, from, to);
		this.con = context;
		this.cols = from;
		this.views = to;
		
		setViewBinder(new SimpleCursorAdapter.ViewBinder() {
			
			private Map<Integer, String> produceIds = null; // cache
			
			public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
				
				if (!(view instanceof TextView)) { 
					return false;
				}
				TextView text = (TextView) view; // TODO: is this the right view?

				/* Special Case: Is Synchronized */
				if (cursor.getColumnName(columnIndex).equals(_IS_SYNCED)) {
					boolean synced = (cursor.getInt(columnIndex) == TRUE);
					text.setText(con.getString(synced ? R.string.saleitem_synced_yes : R.string.saleitem_synced_no));
				} 
				/* Special Case: Produce Name and Id */
				else if (cursor.getColumnName(columnIndex).equals(SALE_PRODUCE_ID)) {
					
					if (produceIds == null) { // populate cache
						String languageCode = con.getString(R.string.languageCode);
						produceIds = ProduceDataOpener.getProduceIds(con, languageCode);
					}
					
					int prodId = cursor.getInt(columnIndex);
					String prodName = produceIds.get(prodId);
					text.setText(con.getString(R.string.saleitem_produce_format, prodName, prodId), TextView.BufferType.SPANNABLE);
				}
				/* General Case: All other fields, let the generic ViewBinder / setViewText method handle it */
				else {
					return false;
				}
				return true;
			}
		});
	}
	
}
